package com.yuanian.timingwheel.context;

import org.springframework.beans.BeansException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.BeanDefinition;
import org.springframework.context.ApplicationContext;
import org.springframework.context.ApplicationContextAware;
import org.springframework.context.annotation.Lazy;
import org.springframework.context.support.AbstractApplicationContext;
import org.springframework.core.env.Environment;
import org.springframework.lang.Nullable;
import org.springframework.stereotype.Component;

/**
 * spring应用上下文
 */
@Component
@Lazy(false)
public class SpringContext implements ApplicationContextAware {

    private static ApplicationContext applicationContext;

    @Autowired
    private Environment environment;

    public SpringContext() {
    }

    public void setApplicationContext(ApplicationContext applicationContext) throws BeansException {
        if (SpringContext.applicationContext == null) {
            SpringContext.applicationContext = applicationContext;
        }

    }

    /**
     * 获取application.yml配置的参数值
     * @param param
     * @return
     */
    public static String getProperty(String param) {
        return getApplicationContext().getEnvironment().getProperty(param);
    }

    public static ApplicationContext getApplicationContext() {
        return applicationContext;
    }

    public static Object getBean(String name) {
        return getApplicationContext().getBean(name);
    }

    public static <T> T getBean(Class<T> clazz) {
        return getApplicationContext().getBean(clazz);
    }

    public static String[] getBeanNamesForType(@Nullable Class<?> type) {
        return ((AbstractApplicationContext)getApplicationContext()).getBeanFactory().getBeanNamesForType(type);
    }

    public static BeanDefinition getBeanDefinition(String name) {
        return ((AbstractApplicationContext)getApplicationContext()).getBeanFactory().getBeanDefinition(name);
    }

    public Environment getEnvironment() {
        return environment;
    }
}


